/*
 * 
 * 
 */

import java.io.IOException;
import java.sql.ResultSet;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utility.SplitString;
import utility.Splitstring;

import database.RecordSearch;
import dbmanager.DBManager;
import dbmanager.GetIdName;

/**
 * Servlet implementation class for Servlet: ResponseServlet
 *
 */
 public class ResponseServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public ResponseServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		String page = (String)session.getAttribute("page");
		
		GetIdName get = new GetIdName();
		
		Hashtable<Object, Object> condition = new Hashtable<Object, Object>();		
		condition.put("mid", get.getId(page));
		condition.put("pid", get.getId("nextpage"));
		condition.put("td","null");
		
		RecordSearch rec = new RecordSearch();
		rec.setConditionMap(condition);
		
		ResultSet rs = rec.getResultSet();
		String nextpage = null;
		try
		{
			while(rs.next())
			{
				nextpage = get.getItem(rs.getString("PV"));
				if(nextpage.equalsIgnoreCase("no$"))
					nextpage = rs.getString("VT");
			}
		}
		catch (Exception e) {
		}
		
		String url = "RequestHandlerServlet";
		String query_str = "",page1 = nextpage;
		
		if(nextpage.contains("?"))
		{
			query_str = page1.replace('?', ':').split(":")[1];	
			url = url +"?"+query_str;			
		}
		
		if(nextpage.contains(".html"))
			page1 = nextpage.split(".html")[0];
		else
			page1 = nextpage;
		
		session.setAttribute("page", page1);
		
		request.getRequestDispatcher(url).forward(request, response);	
	}
}